package com.lxk.controller;

import com.lxk.bean.DbConfig;
import com.lxk.bean.TableInfo;
import com.lxk.service.CodeGeneratorService;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

@RestController
@RequestMapping("/codegen")
public class CodeGeneratorController {

    private final CodeGeneratorService codeGeneratorService;

    public CodeGeneratorController(CodeGeneratorService codeGeneratorService) {
        this.codeGeneratorService = codeGeneratorService;
    }

    @PostMapping("/tables")
    public List<TableInfo> getTables(@RequestBody DbConfig dbConfig) throws Exception {
        try (Connection conn = DriverManager.getConnection(
                dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword())) {
            return codeGeneratorService.getTables(conn);
        }
    }

    @PostMapping("/generate")
    public String generate(@RequestBody DbConfig dbConfig,
                           @RequestParam("outputPath") String outputPath) throws Exception {
        try (Connection conn = DriverManager.getConnection(
                dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword())) {
            codeGeneratorService.generateCode(conn, outputPath);
        }
        return "代码生成成功";
    }
}

